﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using RentIt06WPFClient;
using RentIt06WPFClient.AdminSession;
using RentIt06WPFClient.CreateAccountSession;
using RentIt06WPFClient.FileService;
using RentIt06WPFClient.PublisherSession;
using RentIt06WPFClient.UserSession;
using Account = RentIt06WPFClient.UserSession.Account;
using PermissionGroup = RentIt06WPFClient.UserSession.PermissionGroup;

namespace RentIt06WPFClient {
    class Session {
        private static Session Instance;
        public static AdminSessionClient Admin {get { return Instance._admin; }}
        public static PublisherSessionClient Publisher { get { return Instance._publisher; } }
        public static UserSessionClient User { get { return Instance._user; } }
        public static CreateAccountSessionClient CreateAccount { get { return _createAccount; } }
        public static FileServiceClient FileService { get { return _fileService; } }
        private readonly AdminSessionClient _admin;
        private readonly PublisherSessionClient _publisher;
        private readonly UserSessionClient _user;
        private static readonly CreateAccountSessionClient _createAccount = new CreateAccountSessionClient();
        private static readonly FileServiceClient _fileService = new FileServiceClient();
        private Session() {
            _admin = new AdminSessionClient();
            _publisher = new PublisherSessionClient();
            _user = new UserSessionClient();
        }


        public static Account Login (string email, string password) {
            if(Instance == null
                || User.State == CommunicationState.Faulted
                || User.State == CommunicationState.Closed) 
                Init();
            Account account;
            try {
                account = User.Login(email, password);
            } catch (FaultException e) {
                if (e.Code.Name == "401") throw new Exception("Login failed due to bad email-password combination.");
                throw new IOException("Service did not response or a fault happend at the server", e);
            }
            switch (account.Permission) {
                case PermissionGroup.Admin:
                    Admin.Login(email, password);
                    Publisher.Login(email, password);
                    break;
                case PermissionGroup.Publisher:
                    Publisher.Login(email, password);
                    break;
            }
            return account;
        }
        public static void Init() {
            Instance = new Session();
        }
    }
}
